def decoding(code,item_list,W,func):
    p = 0
    w = 0
    for i in code:
        item = item_list[i-1]
        if w+item[0] > W:
            break
        p += item[0]
        w += item[1]
    print(p,w) 
    return func(p,w)

item_list = [[30,40],
            [60,40],
            [25,30],
            [8,5],
            [10,5],
            [40,35],
            [60,30]]
W = 120
backpack= lambda p,w: p*(1- ((1/ abs(w-W))/max(W,abs(w-W))))
codes = [[6,4,3,5,7,1,2],
        [7,2,4,3,5,6,1],
        [1,3,4,2,6,5,7],
        [2,7,3,1,5,4,6],
        [5,3,2,4,7,6,1]]

fitness = []
for code in codes:
    print('code:')
    print(code)
    print('适应值:')
    print(decoding(code,item_list,W,backpack))
    fitness.append(decoding(code,item_list,W,backpack))
sel_po = []
for f in fitness:
    sel_po.append(f/sum(fitness))
for c,f in zip(codes,sel_po):
    print('code:')
    print(c)
    print('选择概率')
    print(sel_po)
